import os
import requests
from retrying import retry
import time
import threading

class PicDownloader(object):


	def __init__(self, headers):
		self.headers = headers

	# 新建文件夹，并且将目录切换到当前文件夹下
	def make_dir(self, root_path, folder_name):
		path = os.path.join(root_path, folder_name)
		print(path)
		if not os.path.exists(path):
			os.makedirs(path)
			os.chdir(path)
		else:
			os.chdir(path)
		return True

	def make_dir_in_current_folder(self, folder_name):
		if not os.path.exists(folder_name):
			os.makedirs(folder_name)
			os.chdir(folder_name)
		else:
			os.chdir(folder_name)
		return True

	# 保存图片到当前的目录下
	@retry(stop_max_attempt_number = 10)
	def save_pic(self, pic_src, pic_name):
		try:
			if os.path.exists("{}.jpg".format(pic_name)):
				return
			time.sleep(0.5)
			img = requests.get(pic_src, headers=self.headers, timeout=10)
			img_name = "{}.jpg".format(pic_name)
			with open(img_name, 'ab') as f:
				f.write(img.content)
				print(img_name)
		except Exception as e:
			raise e
